<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
    org.springframework.context.ApplicationContext spring = org.springframework.web.context.support.WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
    com.lingx.core.service.II18NService i18n = spring.getBean(com.lingx.core.service.II18NService.class);
    org.springframework.jdbc.core.JdbcTemplate jdbc = spring.getBean(org.springframework.jdbc.core.JdbcTemplate.class);
    com.lingx.core.model.bean.UserBean userBean = (com.lingx.core.model.bean.UserBean) session.getAttribute(com.lingx.core.Constants.SESSION_USER);


    com.lingx.core.service.ILingxService lingx = spring.getBean(com.lingx.core.service.ILingxService.class);
    String temp8 = lingx.getConfigValue("lingx.gps.map.windowinfo", "1,400,240");
    String array8[] = temp8.split(",");
    request.setAttribute("WindowInfoType", array8[0]);
    request.setAttribute("WindowInfoWidth", array8[1]);
    request.setAttribute("WindowInfoHeight", array8[2]);
%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>电子围栏</title>
    <link href="js/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <%@ include file="/lingx/include/include_JavaScriptAndCss4.jsp" %>
    <style type="text/css">

        #container {
            height: 100%
        }
        #containermap {
            height: 100%
        }
    </style>
    <script type="text/javascript"
            src="//webapi.amap.com/maps?v=1.4.4&key=861089faa8611ac3b8fcfe5a96afaf6b&plugin=AMap.MapType"></script>

    <script src="js/jsmap.js"></script>
</head>
<body>
<div id="container">
    <div>
        <button id="reset">清除</button>
        <button id="save">保存</button>
    </div>
    <div id="containermap">

    </div>
</div>
<script type="text/javascript">
    var handlerJsp = "<%=basePath%>gps/handler.jsp";
    var store, extParams = {};
    var positions = [];
    var polygon = null;
    var currentCarId = "";

    var latDef = 38.026278;
    var lngDef = 114.648946;
    var map = new AMap.Map('containermap', {
        resizeEnable: true,
        zoom: 14,
        center: [lngDef, latDef]
    });
    map.addControl(new AMap.MapType({
        defaultType: 0
    }));
    map.on('click', function (e) {
        const position = new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat());
        const marker = new AMap.Marker({
            position: position
        });
        map.add(marker);

        positions.push([e.lnglat.getLng(), e.lnglat.getLat()]);
        if (positions.length >= 2) {
            if (polygon != null) {
                polygon.setMap(null);
            }
            polygon = new AMap.Polygon({
                path: positions,
                fillColor: '#ccebc5',
                strokeOpacity: 1,
                fillOpacity: 0.5,
                strokeColor: '#2b8cbe',
                strokeWeight: 1,
            });
            map.add(polygon);

            if (positions.length >= 3) {
                map.setFitView(null, false, [150, 60, 100, 60]);
            }
        }
    });

    Ext.onReady(function () {
        store = Ext.create('Ext.data.TreeStore', {
            id: "treeStore",
            proxy: {
                actionMethods: {
                    create: 'POST',
                    read: 'POST', // by default GET
                    update: 'POST',
                    destroy: 'POST'
                },
                type: 'ajax',
                url: handlerJsp + '?c=getTreeList&checkbox=false&online=false&type=2',
                reader: {
                    type: 'json'
                },
            },
            root: {
                text: "所有 车队",
                id: '0',
                expanded: true
            },
            autoLoad: true,
            listeners: {
                beforeload: function (store) {
                    if (store)
                        Ext.apply(store.proxy.extraParams, extParams);
                },
                load: function () {
                    Ext.getCmp("tree").getSelectionModel().select(0);
                }
            }
        });
        Ext.create('Ext.Viewport', {
            id: 'viewport',
            layout: 'border',
            border: false,
            style: "padding:2px",
            items: [{
                id: 'tree',
                region: "west",
                split: true,
                width: 280,
                //closable: true,
                animate: false,
                autoScroll: true,
                rootVisible: false,
                store: store,
                xtype: "tree",
                dockedItems: [{
                    xtype: 'toolbar',
                    items: [{
                        id: "SearchText",
                        xtype: 'textfield',
                        name: 'field1',
                        width: 110,
                        emptyText: '车牌/ID/分组',
                        listeners: {
                            specialkey: function (field, e) {
                                if (e.getKey() == e.ENTER) {
                                    var text = Ext.getCmp("SearchText").getValue();
                                    extParams["text"] = (text);
                                    if (text) {
                                        store.load();
                                    } else {
                                        store.getRootNode().remove();
                                        store.setRootNode({
                                            text: "ROOT",
                                            id: "0",
                                            expanded: true
                                        });
                                    }
                                }
                            }
                        }
                    }, {
                        text: "查询", handler: function () {
                            var text = Ext.getCmp("SearchText").getValue();
                            extParams["text"] = (text);
                            if (text) {
                                store.load();
                            } else {
                                store.getRootNode().remove();
                                store.setRootNode({
                                    text: "ROOT",
                                    id: "0",
                                    expanded: true
                                });
                            }

                        }
                    }, {
                        text: "刷新",
                        handler: function () {
                            window.location.reload();
                        }
                    }],
                    dock: 'top',
                    displayInfo: true
                }],
                listeners: {
                    itemdblclick: function (view, record, item, index, event, obj) {
                        var node = record;
                        var temp = node.data.id;
                        getCarFence(temp.substring(temp.lastIndexOf("_") + 1), node.data.text);
                    },

                    itemcontextmenu: function (view, record, item, index, e) {
                        if (record.data.id.indexOf("_") > 0) {
                            e.preventDefault();
                            e.stopEvent();
                            var car_menu = createCarMenu(record);
                            car_menu.showAt(e.getXY());
                        }

                    }

                }
            },

                {
                    region: "center",

                    id: 'gmap',
                    //border:false,
                    contentEl: "container"

                }]


        }).show();

        $("#reset").click(function(){
            map.clearMap();
            positions = [];
        });

        $("#save").click(function(){
            if (currentCarId == "") {
                alert("请选择车辆");
                return;
            }
            if (positions.length <= 2
                && positions.length >= 1) {
                alert("围栏不完整");
                return;
            }
            var r = confirm("确定要保存吗？");
            if (r == true) {
                var allPositions = positions.toString();
                $.post(handlerJsp, {c: "saveFence", carid: currentCarId, positions: allPositions}, function (json) {
                    alert("保存成功");
                }, "json");
            }
        });
    });

    function getCenter(PolygonArr) {
        let total = PolygonArr.length;
        let X = 0; let Y = 0; let Z = 0;
        PolygonArr.forEach((lnglat) => {
            let lng = lnglat[0] * Math.PI / 180;
            let lat = lnglat[1] * Math.PI / 180;
            let x, y, z;
            x = Math.cos(lat) * Math.cos(lng);
            y = Math.cos(lat) * Math.sin(lng);
            z = Math.sin(lat);
            X += x;
            Y += y;
            Z += z;
        });
        X = X / total;
        Y = Y / total;
        Z = Z / total;

        let Lng = Math.atan2(Y, X);
        let Hyp = Math.sqrt(X * X + Y * Y);
        let Lat = Math.atan2(Z, Hyp);
        console.log(Lng, Lat, Hyp);
        return [Lng * 180 / Math.PI, Lat * 180 / Math.PI];
    }

    function getCarFence(carid, carno) {
        map.clearMap();
        positions = [];
        currentCarId = carid;
        $.post(handlerJsp, {c: "getFence", carid: currentCarId}, function (json) {
            if (json.hasOwnProperty('fence') == true) {
                var fence = json['fence'];
                var allPositions = fence.split(",");
                allPositions.forEach(function(item,index,allPositions){
                    if (index % 2 == 0) {
                        positions.push([allPositions[index], allPositions[index+1]]);
                    }
                })
                if (positions.length > 2) {
                    var centerPos = getCenter(positions);
                    map.setZoomAndCenter(14, centerPos);

                    polygon = new AMap.Polygon({
                        path: positions,
                        fillColor: '#ccebc5',
                        strokeOpacity: 1,
                        fillOpacity: 0.5,
                        strokeColor: '#2b8cbe',
                        strokeWeight: 1,
                    });
                    map.add(polygon);

                    map.setFitView(null, false, [150, 60, 100, 60]);
                }
            } else {
                if (json.hasOwnProperty('lat') == true
                    && json.hasOwnProperty('lng') == true) {
                    var lat = json['lat'];
                    var lng = json['lng'];
                    if (lat == 0 || lng == 0) {
                        lat = latDef;
                        lng = lngDef;
                    }
                    map.setZoomAndCenter(14, [lng, lat]);
                }
            }
        }, "json");
    }

</script>
</body>
</html>
